package com.hf.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hf.entity.RoleModules;
import com.hf.service.IRoleModulesService;
import com.hf.util.Result;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author eight
 * @since 2021-06-06
 */
@RestController
@RequestMapping("/role-modules")
public class RoleModulesController {
	@Autowired
	IRoleModulesService iRoleModulesService;

	/**
	 * 根据角色id给角色设置权限
	 * 
	 * @param roleId
	 * @param mids
	 * @return
	 */
	@PostMapping("/insertBatch")
	public Object insertBatch(@RequestParam Integer roleId, @RequestParam String mids) {

		// 中间表批量删除
		QueryWrapper<RoleModules> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("role_id", roleId);
		iRoleModulesService.remove(queryWrapper);
		// 中间表批量添加
		List<RoleModules> list = new ArrayList<RoleModules>();
		if (mids.length() != 0) {
			String[] split2 = mids.split(",");
			for (String m : split2) {
				list.add(new RoleModules(roleId, Integer.valueOf(m)));
			}
		} else {
			return new Result(0, "已移除所有模块");
		}

		if (iRoleModulesService.saveBatch(list)) {
			return new Result(0, "设置成功");
		}
		return new Result(1, "设置失败");

	}

	/**
	 * 移除角色的权限
	 * 
	 * @param roleId
	 * @param mids
	 * @return
	 */
	@PostMapping("/deleteBatch")
	public Object deleteBatch(@RequestParam Integer roleId, @RequestParam String mids) {
		boolean res = iRoleModulesService.deleteByRoleIdAndModuleId(roleId, mids);
		if (res) {
			return new Result(0, "移除成功");
		}
		return new Result(1, "移除失败");
	}

}
